package ynu.edu.elmservlet.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import ynu.edu.elmservlet.po.User;
import ynu.edu.elmservlet.service.UserService;
import ynu.edu.elmservlet.service.impl.UserServiceImpl;
import ynu.edu.elmservlet.util.JWTUtil;
import jakarta.servlet.http.HttpServletRequest;

import java.io.BufferedReader;
import java.util.HashMap;
import java.util.Map;

public class UserController {
    private final ObjectMapper objectMapper = new ObjectMapper();

    public Object login(HttpServletRequest request) throws Exception {
        try {
            // 读取请求体
            BufferedReader reader = request.getReader();
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            
            // 解析JSON
            Map<String, String> loginData = objectMapper.readValue(sb.toString(), Map.class);
            String userId = loginData.get("userId");
            String password = loginData.get("password");
            
            System.out.println("Login attempt - userId: " + userId);
            System.out.println("Login attempt - password: " + password);
            System.out.println("Content-Type: " + request.getContentType());
            
            // 参数验证
            if (userId == null || password == null || userId.trim().isEmpty() || password.trim().isEmpty()) {
                Map<String, String> error = new HashMap<>();
                error.put("message", "用户名或密码不能为空");
                return error;
            }
            
            UserService service = new UserServiceImpl();
            User user = service.getUserByIdByPass(userId, password);
            
            if (user != null) {
                // 生成token
                String token = JWTUtil.generateToken(user.getUserId());
                
                // 构造返回对象
                Map<String, Object> result = new HashMap<>();
                result.put("token", token);
                
                // 处理用户信息，去除敏感字段
                user.setPassword(null);
                result.put("user", user);
                
                return result;
            } else {
                // 登录失败返回错误信息
                Map<String, String> error = new HashMap<>();
                error.put("message", "用户名或密码错误");
                return error;
            }
        } catch (Exception e) {
            System.out.println("Login error: " + e.getMessage());
            Map<String, String> error = new HashMap<>();
            error.put("message", "服务器错误：" + e.getMessage());
            return error;
        }
    }

    public Object checkUserId(HttpServletRequest request) throws Exception{
        String userId = request.getParameter("userId");
        UserService service = new UserServiceImpl();
        int result = service.getUserById(userId);
        return result;
    }

    public Object register(HttpServletRequest request) throws Exception{
        User user = new User();
        user.setUserId(request.getParameter("userId"));
        user.setPassword(request.getParameter("password"));
        user.setUserName(request.getParameter("userName"));
        user.setUserSex(Integer.valueOf(request.getParameter("userSex")));
        UserService service = new UserServiceImpl();
        int result = service.saveUser(user);
        return result;
    }
}